﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using HtmlAgilityPack;

namespace Downloader
{
    public class DownloadExtension
    {
        /// <summary>
        /// Gets the HTML from URL.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <returns></returns>
        public static string GetHtmlFromUrl(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // get the response stream.
            // use a stream reader that understands UTF8
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string html = reader.ReadToEnd();
            // close the reader
            reader.Close();
            response.Close();
            return html;//return conten html
        }

        /// <summary>
        /// Gets the topic ID from URL.
        /// </summary>
        /// <param name="originalURL">The original URL.</param>
        /// <returns></returns>
        public static string GetTopicIDFromURL(string originalURL)
        {
            var regex = new Regex(@"t=(\d+)");
            var match = regex.Match(originalURL);
            if (match.Success)
            {
                return match.Groups[1].Value;
            }

            return "Untitled";
        }

        /// <summary>
        /// Gets the title from HTML.
        /// </summary>
        /// <param name="htmlContent">Content of the HTML.</param>
        /// <returns></returns>
        public static string GetTitleFromHTML(string htmlContent)
        {
            try
            {
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(htmlContent);
                HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//title");
                if (nodes != null && nodes.Count > 0)
                {
                    return nodes[0].InnerText;
                }
            }
            catch (Exception)
            {
                
            }

            return "Untitled";
        }

        /// <summary>
        /// Builds the file name from title.
        /// </summary>
        /// <param name="title">The title.</param>
        /// <returns></returns>
        public static string BuildFileNameFromTitle(string title)
        {
            string fileName = title;
            foreach (char lDisallowed in Path.GetInvalidFileNameChars())
            {
                fileName = fileName.Replace(lDisallowed.ToString(), "");
            }
            return fileName.Replace(" ", "-");
        }

        /// <summary>
        /// Gets the max page from HTML.
        /// </summary>
        /// <param name="htmlContent">Content of the HTML.</param>
        /// <returns></returns>
        public static int GetMaxPageFromHTML(string htmlContent)
        {
            try
            {
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(htmlContent);
                HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class='pagenav']/table/tr/td[@class='alt1']/a[@href]");

                if (nodes != null)
                {
                    string href = nodes[nodes.Count-1].GetAttributeValue("href" ,"");
                    if (href != "")
                    {
                        var regex = new Regex(@"page=(\d+)");
                        var match = regex.Match(href);
                        if (match.Success)
                        {
                            return int.Parse(match.Groups[1].Value);
                        }
                    }

                    //                if (nodes != null && nodes.Count > 0)
                    //                {
                    //                    return nodes[0].InnerText;
                    //                }
                }
            }
            catch (Exception)
            {

            }

            return 1;
        }
    }
}
